package com.ltu.timkor6.gamesite.games.towerofhanoi.server;

import com.ltu.timkor6.gamesite.games.towerofhanoi.client.TowerOfHanoiService;
import com.ltu.timkor6.gamesite.server.DataBaseConnection;
import com.ltu.timkor6.gamesite.server.GameSiteServiceImpl;
import com.ltu.timkor6.gamesite.shared.Result;

@SuppressWarnings("serial")
public class TowerOfHanoiServiceImpl extends GameSiteServiceImpl implements TowerOfHanoiService
{
	private Result result;
		
	private int minimumMoves;
	
	public TowerOfHanoiServiceImpl()
	{
		this.result = new Result();
		this.result.setGameTitle("TowerOfHanoi");
	}
	
	/**
	 * First time, starting game.
	 */
	public int start(int elements)
	{
		this.result.setTurns(elements);
		
		this.minimumMoves = (int) (Math.pow(2, elements) - 1);
		
		return this.minimumMoves;
	}
	
	/**
	 * Check an answer and return given points.
	 */
	public Result finished(int moves)
	{
		if(this.minimumMoves <= moves)
		{
			int points = givePoints(moves);
			this.result.setPoints(points);
			
			if(this.userInfo != null)
			{
				new DataBaseConnection(this).addResult(result);
			}
			
			return result;
		}
		else
		{
			return null;
		}
	}
	
	/**
	 * Calculate points.
	 * @return
	 */
	private int givePoints(int moves)
	{
		int points = 0;
		
		// The more elements the bigger score
		points += this.result.getTurns() * 10;
		
		// The more extra moves the lesser score
		points -= moves - this.minimumMoves;
		
		return points;
	}
}
